﻿using System.Data;
using System.Data.SqlServerCe;
using System.Collections.Generic;
using Home.Mobilesales.Common;
using Home.MobileSales.Common.Entities;


namespace Home.MobileSales.Common.Models
{
    public class BuyerRepository
    {

        public Buyer GetBuyerById(int id)
        {
            using (SqlCeConnection connection = WorkDataBase.CreateConnection())
            {
                if (connection.State != ConnectionState.Open)
                    connection.Open();

                string sqlQuery = "SELECT NameClient, IdBuyer FROM Buyers where IdBuyer = @id";
                using (SqlCeCommand command = new SqlCeCommand(sqlQuery, connection))
                {
                    command.Parameters.Add("@id", id);
                    using (SqlCeDataReader dr = command.ExecuteReader())
                    {
                        if (!dr.Read())
                            return null;
                        int idBuyer = dr.GetOrdinal("IdBuyer");
                        int nameClient = dr.GetOrdinal("NameClient");
                        Buyer buyer = new Buyer();
                        buyer.IdBuyer = dr.GetInt32(idBuyer);
                        buyer.NameBuyer = dr.GetString(nameClient);
                        return buyer;
                    }
                }

            }
        }

        public List<Buyer> GetBuyers()
        {
            List<Buyer> buyers = new List<Buyer>();
            using (SqlCeConnection connection = WorkDataBase.CreateConnection())
            {
                if (connection.State != ConnectionState.Open)
                    connection.Open();

                string sqlQuery = "SELECT NameClient, IdBuyer FROM Buyers";
                using (SqlCeCommand command = new SqlCeCommand(sqlQuery, connection))
                {
                    using (SqlCeDataReader dr = command.ExecuteReader())
                    {
                        int idBuyer = dr.GetOrdinal("IdBuyer");
                        int nameClient = dr.GetOrdinal("NameClient");
                        while (dr.Read())
                        {
                            Buyer buyer = new Buyer();
                            buyer.IdBuyer = dr.GetInt32(idBuyer);
                            buyer.NameBuyer = dr.GetString(nameClient);
                            buyers.Add(buyer);
                        }
                        return buyers;
                    }
                }
            }

        }
    }
}
